package medium;

import java.util.Arrays;

public class T16 {
    public static void main(String[] args) {
        System.out.println(threeSumClosest(new int[] {-1, 2, 1, -4}, 1));
    }

    static int threeSumClosest(int[] nums, int target) {
        // 排序
        Arrays.sort(nums);
        int min = Integer.MAX_VALUE;
        int t = 0;
        // 第一层循环
        for (int a = 0; a < nums.length - 2; a++) {
            // 双指针b，c
            int b = a + 1;
            int c = nums.length - 1;
            while (b < c) {
                int sum = nums[a] + nums[b] + nums[c];
                int result = sum - target;
                if (result < 0) {
                    if (Math.abs(result) < min) {
                        min = Math.abs(result);
                        t = sum;
                    }
                    // 下一个不相等的数
                    while (b < c && nums[b] == nums[++b]) {
                    }
                } else if (sum - target == 0) {
                    return sum;
                } else {
                    if (Math.abs(result) < min) {
                        min = Math.abs(result);
                        t = sum;
                    }
                    // 下一个不相等的数
                    while (b < c && nums[c] == nums[--c]) {
                    }
                }

            }
        }
        return t;
    }
}
